<template>
  <div>
    <a-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="auto">
      <a-form-item label="合同名称" prop="projectName">
        <a-input v-model="queryParams.projectName" placeholder="请输入合同名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </a-form-item>
      <a-form-item label="合同状态" prop="projectStatus">
        <a-select v-model="queryParams.projectStatus" placeholder="请选择合同状态" clearable size="small">
          <a-option v-for="dict in projectStatusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </a-select>
      </a-form-item>
      <a-form-item label="客户名称" prop="providerName">
        <a-input v-model="queryParams.providerName" placeholder="请输入客户名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </a-form-item>
      <a-form-item label="所属组织" prop="unitName" v-if="showUnitSearch">
        <a-input v-model="queryParams.unitName" placeholder="请输入所属组织" clearable size="small" @keyup.enter.native="handleQuery" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" icon="a-icon-search" size="mini" @click="handleQuery">搜索</a-button>
        <a-button icon="a-icon-refresh" size="mini" @click="resetQuery">重置</a-button>
      </a-form-item>
    </a-form>

    <a-row :gutter="10" class="mb8">
      <a-col :span="1.5">
        <a-button type="primary" plain icon="a-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['order:project:add']">新增</a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button type="success" plain icon="a-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['order:project:edit']">
          修改</a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button type="danger" plain icon="a-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['order:project:remove']">删除</a-button>
      </a-col>
      <a-col :span="1.5">
        <a-button type="warning" plain icon="a-icon-download" size="mini" @click="handleExport" v-hasPermi="['order:project:export']">导出</a-button>
      </a-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </a-row>

    <a-table v-loading="loading" :border="true" :data="projectList" @selection-change="handleSelectionChange">
      <a-table-column type="selection" width="55" align="center" />
      <a-table-column type="index" label="序号" width="55" align="center" />
      <!--<a-table-column label="主键" align="center" prop="id" />-->
      <a-table-column label="合同名称" align="center" prop="projectName" />
      <a-table-column label="合同类型" align="center" prop="projectType" />
      <a-table-column label="合同编号" align="center" prop="projectNumber" />
      <a-table-column label="合同描述" align="center" prop="projectDescr" />
      <a-table-column label="合同状态" align="center" prop="projectStatus" :formatter="projectStatusFormat" />
      <a-table-column label="合同期限" align="center" prop="projectMount" />
      <a-table-column label="签订时间" align="center" prop="projectStartTime" />
      <a-table-column label="结束时间" align="center" prop="projectEndTime" />
      <a-table-column label="客户名称" align="center" prop="providerName" />
      <a-table-column label="所属组织" align="center" prop="unitName" />
      <!--
      <a-table-column label="项目地址" align="center" prop="address" />
      -->
      <a-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <a-button size="mini" type="text" icon="a-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['order:project:edit']">修改</a-button>
          <a-button size="mini" type="text" icon="a-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['order:project:remove']">删除
          </a-button>
        </template>
      </a-table-column>
    </a-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    <br />

    <!-- 添加或修改合同对话框 -->
    <a-modal :title="title" :visible.sync="open" width="720px" append-to-body>
      <a-form ref="form" :model="form" :rules="rules" label-width="120px">
        <a-form-item label="合同名称" prop="projectName">
          <a-input v-model="form.projectName" placeholder="请输入合同名称" />
        </a-form-item>
        <a-form-item label="合同类型" prop="projectType">
          <a-input v-model="form.projectType" placeholder="请输入合同类型" />
        </a-form-item>
        <a-form-item label="合同编号" prop="projectNumber">
          <a-input v-model="form.projectNumber" placeholder="请输入合同编号" />
        </a-form-item>
        <a-form-item label="合同描述" prop="projectDescr">
          <a-input v-model="form.projectDescr" placeholder="请输入合同描述" />
        </a-form-item>
        <a-form-item label="合同状态">
          <a-radio-group v-model="form.projectStatus">
            <a-radio v-for="dict in projectStatusOptions" :key="dict.dictValue" :label="dict.dictValue">{{dict.dictLabel}}</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="所属组织" prop="unitId">
          <VueTreeSelect v-model="form.unitId" :options="unitOptions" :normalizer="getUnitFormatter" :default-expand-level="3" :show-count="true"
            placeholder="请选择归属组织" />
        </a-form-item>
        <a-form-item label="客户名称" prop="providerId">
          <VueTreeSelect v-model="form.providerId" :options="providerOptions" :normalizer="getUnitFormatter" :default-expand-level="3"
            :show-count="true" placeholder="请选择客户组织" />
        </a-form-item>
        <a-form-item label="签订时间" prop="projectStartTime">
          <a-date-picker v-model="form.projectStartTime" type="date" placeholder="请选择日期" @change="projectTimeChange"></a-date-picker>
        </a-form-item>
        <a-form-item label="合同期限" prop="projectMount">
          <a-input-number v-model="form.projectMount" :precision="1" :step="0.1" :min="0.1" :max="99" @change="projectTimeChange"></a-input-number>
          <span>&nbsp;年</span>
        </a-form-item>
        <a-form-item label="结束时间" prop="projectEndTime">
          <a-date-picker v-model="form.projectEndTime" type="date" placeholder="请选择日期" :disabled="true"></a-date-picker>
        </a-form-item>
        <!--
        <a-form-item label="项目地址" prop="address">
          <a-input v-model="form.address" placeholder="请输入项目地址" />
        </a-form-item>
        <a-form-item label="地图标识" prop="addrPoint">
          <a-input v-model="form.addrPoint" placeholder="请输入地图标识" />
        </a-form-item>
        <a-form-item label="备用字段" prop="remark">
          <a-input v-model="form.remark" placeholder="请输入备用字段" />
        </a-form-item>
        -->
      </a-form>
      <div slot="footer" class="dialog-footer">
        <a-button type="primary" @click="submitForm">确 定</a-button>
        <a-button @click="cancel">取 消</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
  import {
    listProject,
    getProject,
    delProject,
    addProject,
    updateProject
  } from "@/api/order/project";
  import {
    listDept
  } from "@/api/system/dept";
  import VueTreeSelect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "ProjectTable",
    components: {
      VueTreeSelect
    },
    props: {
      showUnitSearch: {
        type: Boolean,
        default: true
      },
      ancestorsProvider: {
        type: Number,
        default: 0
      },
      ancestorsServicer: {
        type: Number,
        default: 0
      }
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 合同表格数据
        projectList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 合同状态字典
        projectStatusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          projectName: null,
          projectStatus: null,
          providerId: null,
          providerName: null,
          unitId: null,
          unitName: null,
        },
        // 组织树选项
        unitOptions: undefined,
        providerOptions: undefined,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          unitId: [{
            required: true,
            message: "所属组织不能为空",
            trigger: "blur"
          }],
          providerId: [{
            required: true,
            message: "客户组织不能为空",
            trigger: "blur"
          }],
          projectName: [{
            required: true,
            message: "合同名称不能为空",
            trigger: "blur"
          }],
          projectType: [{
            required: true,
            message: "合同类型不能为空",
            trigger: "blur"
          }],
          projectNumber: [{
            required: true,
            message: "合同编号不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    created() {
      this.getList();
      this.getUnitList();
      this.getDicts("service.project.status").then(response => {
        this.projectStatusOptions = response.data;
      });
    },
    methods: {
      projectTimeChange() {
        if (this.form.projectStartTime && this.form.projectMount) {
          let tempDate = new Date(this.form.projectStartTime);
          let tempDay = parseInt(this.form.projectMount * 365);
          tempDate.setDate(tempDate.getDate() + tempDay);
          this.form.projectEndTime = tempDate;
        }
      },
      /** 查询组织下拉树结构 */
      getUnitList() {
        listDept({
          ancestors: this.ancestorsServicer
        }).then(response => {
          let unitOptions = this.handleTree(response.data, "deptId");
          if (unitOptions && unitOptions.length == 1 && unitOptions[0].deptId == this.ancestorsServicer) {
            unitOptions = unitOptions[0].children;
          }
          this.unitOptions = unitOptions;
        });
        listDept({
          ancestors: this.ancestorsProvider
        }).then(response => {
          let unitOptions = this.handleTree(response.data, "deptId");
          if (unitOptions && unitOptions.length == 1 && unitOptions[0].deptId == this.ancestorsProvider) {
            unitOptions = unitOptions[0].children;
          }
          this.providerOptions = unitOptions;
        });
      },
      /** 转换组织数据结构 */
      getUnitFormatter(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        };
      },
      /** 查询合同列表 */
      getList() {
        this.loading = true;
        listProject(this.queryParams).then(response => {
          this.projectList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 合同状态字典翻译
      projectStatusFormat(row, column) {
        return this.selectDictLabel(this.projectStatusOptions, row.projectStatus);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          projectName: null,
          projectType: null,
          projectNumber: null,
          projectDescr: null,
          projectStatus: "0",
          projectMount: "1.0",
          providerId: null,
          providerName: null,
          unitId: null,
          unitName: null,
          address: null,
          addrPoint: null,
          createBy: null,
          createTime: null,
          remark: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加合同";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getProject(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改合同";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateProject(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addProject(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除合同编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProject(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('order/project/export', {
          ...this.queryParams
        }, `order_project.xlsx`)
      }
    }
  };
</script>
